<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="java.net.*"%>
<%
    String path = request.getContextPath();
    String ip=request.getRemoteAddr();
    String ipServer=InetAddress.getLocalHost().getHostAddress();
    int port = request.getServerPort();
    System.out.println(ip+">>>"+ipServer+">>"+port);
%>
<html>
<head>
    <title>websocket</title>
    <script type="text/javascript" src="<%=path%>/js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        var IPSERVER = '<%=ipServer%>';
        var PORT = '<%=port%>';
        var PATH = '<%=path%>';
        var ws;
        function ToggleConnectionClicked() {
            try {
                var url = "ws://"+IPSERVER+":"+PORT+PATH+"/socket";
                ws = new WebSocket(url);//连接服务器
                //0 尚未连接
                //1已经建立连接，可以进行通讯
                //2通过关闭握手，正在关闭连接
                //3表示连接已关闭或无法打开
                //读属性的bufferedAmount代表文本的字节数,utf-8的排队使用send()方法。
                //var bufferedAmount = ws.bufferedAmount;
                var textarea = $("#text");
                textarea.append("准备连接到服务器...\r\n");
                ws.onopen = function(event) {
                    textarea.append("已经与服务器建立了连接\r\n");
                    console.log("已经与服务器建立了连接-当前连接状态>>>" + this.readyState);
                };
                ws.onclose = function(event) {
                    textarea.append("已经与服务器断开连接\r\n");
                    console.log("已经与服务器断开连接-当前连接状态>>>" + this.readyState);
                };
                ws.onmessage = function(event) {
                    var value = eval("("+event.data+")");
                    textarea.append(value.name+":"+value.text+"\r\n");

                    console.log("接收到服务器发送的数据>>>" + event.data);
                };
                ws.onerror = function(event) {
                    console.log("WebSocket异常！");
                };
            } catch (ex) {
                console.log(ex.message);
            }
        };
        //向服务器发送数据
        function SendData() {
            var send_value = $("#send_value");
            try {
                ws.send(send_value.val());
                send_value.val("");
            } catch (ex) {
                console.log(ex.message);
            }
        };

        function close_break(){
            ws.close();
        }
    </script>
</head>
<body>
    <button id='ToggleConnection' type="button" onclick='ToggleConnectionClicked();'>连接服务器</button> <br />
    <textarea rows="20" cols="60" id="text" disabled="disabled" style="font-size: 12px;color: red;"></textarea><br>
    <input  id="send_value" type="text">&nbsp;&nbsp;<input type="button" onclick="SendData();" value="发送"><br/>
    <button type="button" onclick='close_break();'>断开连接</button>
</body>
</html>
